const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const { app } = require('electron');
const isDev = require('electron-is-dev');

async function scanPrefabFiles(dirPath) {
  const uuids = new Set();
  const results = {
    scanTime: new Date().toISOString(),
    basePath: dirPath,
    files: []  // 用于存储每个文件的扫描结果
  };

  async function scanDirectory(currentPath) {
    const entries = await fs.promises.readdir(currentPath, { withFileTypes: true });
    
    for (const entry of entries) {
      const fullPath = path.join(currentPath, entry.name);
      
      if (entry.isDirectory()) {
        await scanDirectory(fullPath);
      } else if (
        entry.isFile() && 
        path.extname(entry.name) === '.prefab'
      ) {
        await processPrefabFile(fullPath);
      }
    }
  }

  async function processPrefabFile(filePath) {
    try {
      const content = await readFile(filePath, 'utf8');
      const jsonArray = JSON.parse(content);
      
      const fileResult = {
        path: path.relative(dirPath, filePath),
        spriteFrameUuids: new Set()  // 改用Set来存储
      };

      if (!Array.isArray(jsonArray)) {
        console.log(`文件 ${filePath} 顶层不是数组`);
        return;
      }

      // 第一阶段：快速扫描是否存在ParticleSystemEx
      let hasParticleSystem = jsonArray.some(item => 
        item?.__type__ === 'cc.ParticleSystemEx'
      );
      
      if (!hasParticleSystem) return;

      // 检查是否存在任何对象的_atlas.__uuid__不为空
      let hasAtlasUuid = false;
      function checkAtlas(obj) {
        if (obj && typeof obj === 'object') {
          if (obj._atlas?.__uuid__) {
            hasAtlasUuid = true;
            return;
          }
          for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
              const child = obj[key];
              if (Array.isArray(child)) {
                child.forEach(checkAtlas);
              } else if (typeof child === 'object') {
                checkAtlas(child);
              }
            }
          }
        }
      }
      
      // 先检查是否存在_atlas.__uuid__
      jsonArray.forEach(checkAtlas);
      if (!hasAtlasUuid) return;

      // 递归遍历所有对象
      function traverse(obj) {
        if (obj && typeof obj === 'object') {
          // 提取ParticleSystemEx的spriteFrame
          if (obj.__type__ === 'cc.ParticleSystemEx' && obj._spriteFrame?.__uuid__) {
            uuids.add(obj._spriteFrame.__uuid__);
            fileResult.spriteFrameUuids.add(obj._spriteFrame.__uuid__);
          }
          
          // 递归遍历子对象
          for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
              const child = obj[key];
              if (Array.isArray(child)) {
                child.forEach(traverse);
              } else if (typeof child === 'object') {
                traverse(child);
              }
            }
          }
        }
      }

      // 第二阶段：详细扫描
      jsonArray.forEach(traverse);

      // 只有当找到了UUID才添加到结果中
      if (fileResult.spriteFrameUuids.size > 0) {
        // 转换Set为数组，确保JSON序列化
        fileResult.spriteFrameUuids = Array.from(fileResult.spriteFrameUuids);
        results.files.push(fileResult);
      }
    } catch (err) {
      console.error(`解析文件 ${filePath} 失败:`, err);
    }
  }

  await scanDirectory(dirPath);

  // 返回结果对象和UUID数组
  return {
    scanResults: results,
    uuids: Array.from(uuids)
  };
}

// 添加一个新函数用于保存扫描结果到指定路径
async function saveScanResults(results, outputPath) {
  try {
    // 确保输出目录存在
    const outputDir = path.dirname(outputPath);
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true });
    }

    await writeFile(
      outputPath,
      JSON.stringify(results, null, 2),
      { 
        encoding: 'utf8',
        mode: 0o666 // 设置文件权限为所有用户可读写
      }
    );
    return true;
  } catch (err) {
    console.error(`保存扫描结果失败 (${outputPath}):`, err);
    throw new Error(`保存扫描结果失败: ${err.message}`);
  }
}

module.exports = { scanPrefabFiles, saveScanResults }; 